package controllers

import (
	"encoding/base64"
	"errors"
	"github.com/gin-gonic/gin"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"krm_backend/config"
)

type BasicInfo struct {
	ClusterId string      `json:"clusterId" form:"clusterId"`
	Namespace string      `json:"namespace" form:"namespace"`
	Name      string      `json:"name" form:"name"`
	Item      interface{} `json:"item"`
}

// 优化资源管理初始化代码逻辑
func BasicInit(r *gin.Context, item interface{}) (clientset *kubernetes.Clientset, basicInfo BasicInfo, err error) {
	basicInfo = BasicInfo{}
	basicInfo.Item = item
	// 兼容get和post方法
	requestMethod := r.Request.Method
	if requestMethod == "GET" {
		err = r.ShouldBindQuery(&basicInfo)
	} else if requestMethod == "POST" {
		err = r.ShouldBindJSON(&basicInfo)
	} else {
		err = errors.New("不支持的请求类型")
	}
	if err != nil {
		msg := "请求出错: " + err.Error()
		return nil, basicInfo, errors.New(msg)
	}
	// 获取kubeconfig
	kubeconfig := config.ClusterKubeconfig[basicInfo.ClusterId]
	kubeconfigBytes, err := base64.StdEncoding.DecodeString(kubeconfig)
	if err != nil {
		msg := "base64解析失败"
		return nil, basicInfo, errors.New(msg)
	}
	restConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfigBytes)
	if err != nil {
		msg := "解析kubeconfig错误" + err.Error()
		return nil, basicInfo, errors.New(msg)
	}
	// 创建客户端工具
	clientset, err = kubernetes.NewForConfig(restConfig)
	if err != nil {
		msg := "创建clientset失败" + err.Error()
		return nil, basicInfo, errors.New(msg)
	}
	return clientset, basicInfo, nil
}
